package com.google.code.garbagecan.minastudy.sample2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyServer {
	
	private static final Logger logger = LoggerFactory.getLogger(MyServer.class);
	
	public static void main(String[] args) {
		IoAcceptor acceptor = new NioDatagramAcceptor();

		acceptor.setHandler(new IoHandlerAdapter() {
			
			@Override
			public void sessionCreated(IoSession session) throws Exception {
			}
			
			@Override
			public void sessionOpened(IoSession session) throws Exception {
			}

			@Override
			public void sessionClosed(IoSession session) throws Exception {
			}

			@Override
			public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
			}

			@Override
			public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
				logger.error(cause.getMessage(), cause);
				session.close(true);
			}

			@Override
			public void messageReceived(IoSession session, Object message) throws Exception {
				logger.info("Received message " + receiveData(message));
				sendData(session);
			}

			@Override
			public void messageSent(IoSession session, Object message) throws Exception {
				logger.info("Sent message " + receiveData(message));
			}
			
			private void sendData(IoSession session) {
				String msg = "Goodbye";
				IoBuffer buffer = IoBuffer.allocate(msg.length());
				try {
					buffer.putString(msg, Charset.forName("UTF-8").newEncoder());
				} catch (CharacterCodingException e) {
					logger.error(e.getMessage(), e);
				}
				buffer.flip();
				session.write(buffer);
			}
			
			private String receiveData(Object message) {
				IoBuffer buffer = (IoBuffer) message;
				String msg = null;
				try {
					msg = buffer.getString(Charset.forName("UTF-8").newDecoder());
				} catch (CharacterCodingException e) {
					logger.error(e.getMessage(), e);
				}
				return msg;
			}
		});
		
		try {
			acceptor.bind(new InetSocketAddress(10000));
		} catch (IOException ex) {
			logger.error(ex.getMessage(), ex);
		}
	}
}
